package www.bw.com.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserContolller {

    @PostMapping("/login")
    public String login(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
        }catch (AuthenticationException e){
return e.getMessage();
        }
        return "login success";
    }




    @RequiresPermissions("user:update")
    @GetMapping("/test1")
    public String test1(){
        return "test1";
    }

    @RequiresPermissions("user:add")
    @GetMapping("/test2")
    public String test2(){
        return "test2";
    }


    @GetMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        try {
            response.sendRedirect(request.getContextPath()+"/login.html");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
